package xiaohong.jvm;

import java.lang.ref.WeakReference;

/**
 * 弱引用测试
 */
public class TestWeakRef {

    public static class User {
        public int id = 0;
        public String name = "";

        public User(int id, String name) {
            super();
            this.id = id;
            this.name = name;
        }

        @Override
        public String toString() {
            return "User [id=" + id + ", name=" + name + "]";
        }
    }

    //输出结果如下:
    //弱引用获取实例: User [id=1, name=Test]
    //AfterGc
    //弱引用获取实例: null
    public static void main(String[] args) {
        User u = new User(1,"Test");//u是new User(1,"Test")这个实例的强引用
        WeakReference<User> userWeak = new WeakReference<>(u);//userWeak表示的就是一个弱引用
        u = null;//保证new User(1,"Test")这个实例此时只有userWeak在弱引用, 它的强引用断开了, 所以此时User实例还不会被回收

        System.out.println("弱引用获取实例: " + userWeak.get());
        System.gc();//强制进行垃圾回收, 弱引用会被回收;
        System.out.println("AfterGc");
        System.out.println("弱引用获取实例: " + userWeak.get());
    }


}
